package io.renren.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import io.renren.dao.FileManagerDao;
import io.renren.entity.FileManagerEntity;
import io.renren.service.FileManagerService;
import io.renren.utils.ShortUrl;



@Service("fileManagerService")
public class FileManagerServiceImpl implements FileManagerService {
	
	@Value("${file.path:#{null}}")
    private String filePath;
	
	@Autowired
	private FileManagerDao fileManagerDao;
	
	@Override
	public FileManagerEntity queryObject(Integer id){
		return fileManagerDao.queryObject(id);
	}
	
	@Override
	public List<FileManagerEntity> queryList(Map<String, Object> map){
		return fileManagerDao.queryList(map);
	}
	
	@Override
	public int queryTotal(Map<String, Object> map){
		return fileManagerDao.queryTotal(map);
	}
	
	@Override
	public void save(FileManagerEntity fileManager){
		fileManagerDao.save(fileManager);
	}
	
	@Override
	public void update(FileManagerEntity fileManager){
		fileManagerDao.update(fileManager);
	}
	
	@Override
	public void delete(Integer id){
		deleteOldFile(id);
		fileManagerDao.delete(id);
	}

	private void deleteOldFile(Integer id) {
		FileManagerEntity old = fileManagerDao.queryObject(id);
		if(old != null) {
			File f = new File(old.getFilePath());
			if(f.exists()) f.delete();
		}
	}
	
	@Override
	public void deleteBatch(Integer[] ids){
		for(Integer id : ids) {
			deleteOldFile(id);
		}
		fileManagerDao.deleteBatch(ids);
	}

	@Override
	public void upload(MultipartFile file, FileManagerEntity fileManager) throws IllegalStateException, IOException {
		
		FileManagerEntity old = fileManagerDao.queryByName(file.getOriginalFilename());
		if(old != null) fileManagerDao.delete(old.getId());
		FileManagerEntity entity = new FileManagerEntity();
		String fileName = file.getOriginalFilename();
		String extName = fileName.substring(fileName.lastIndexOf(".") + 1);
		entity.setFileName(fileName);
		entity.setFileExtName(extName);
		entity.setName(fileManager.getName());
		entity.setRemark(fileManager.getRemark());
		entity.setSize(new Long(file.getSize()).intValue());
		
		String path = filePath + file.getOriginalFilename();
		entity.setFilePath(path);
		File f = new File(path);
		if(f.exists()) f.delete();
		entity.setShortUrl(ShortUrl.getShortUrl(file.getOriginalFilename()));
		file.transferTo(new File(path));
		save(entity);
	}

	@Override
	public FileManagerEntity queryByUrl(String url) {
		return fileManagerDao.queryByUrl(url);
	}
	
}
